<?php
namespace App\Http\Models;
use Illuminate\Support\Facades\Session;
use Illuminate\Database\Eloquent\Model;

class TrainOrder extends Model{

    protected $table = 'ttrainbook';

    public $timestamps=true;

    //TBPayed暂时没有用
    protected $fillable = ['TBTrainID', 'TBPayed','TBCustomerID','TBQty','TBPrice','TBName','TBMobile','TBAge','TBSex'];

    //创建订单
    public static function createOrder($input=array())
    {
        $input['TBCustomerID'] = Session::get(User::$session_key);

        $relative=self::where(array_only($input, array('TBCustomerID', 'TBTrainID')))->first();
        $train=Train::where('TID',$input['TBTrainID'])->first();
        if(!$train)
        {
            return false;
        }

        $input['TBPrice']=$input['TBQty']==$train->TQty1?$train->TPrice1:($input['TBQty']==$train->TQty2?$train->TPrice2:($input['TBQty']==$train->TQty3?$train->TPrice3:($input['TBQty']==$train->TQty4?$train->TPrice4:0)));

        if(!$input['TBPrice'])
        {
            return false;
        }

        //检查名额TBQtyRemain


        if (!$relative)
        {
            //订单未创建
            //生产订单 //去支付

            $input['TBPayed']='cancel';

            return self::create($input);

        } else {
            //订单已经创建
            if($relative->TBPayed=='ok')
            {
                return true;
            }else{
                //dd($input);
                $relative->TBPayed='cancel';//待支付
                $input['TBID']=$relative->TBID;
                return $relative->doSave($input);
            }

        }

    }

    public function doSave($input = array())
    {
        $id = array_pull($input, 'TBID');

        if ($id) {
            $input=array_only($input,$this->fillable);
            //dd($input);
            return self::where('TBID',$id)->update($input);
        } else {
            $user=self::create($input);
            return $user;
        }
    }
}